const userModel = require('../db/user')
const bcryptjs = require('bcryptjs')
const jwt = require('jsonwebtoken')
const {resinfo} = require('../utils/utils')
module.exports = {
    userInfo:async function(req,res){
        // const resObj = {
        //   Code:0,
        //   msg:'获取用户信息成功',
        //   data:null
        // }
        // console.log(resObj);
        let {id} = req.params
        let userinfo
        try {
          userinfo = await userModel.findOne({_id:id})
        } catch (error) {
          resinfo(res,1,'用户信息获取失败')
          return 
        }
        if(!userinfo) {
          resinfo(res, 1, '用户信息获取失败！')
          return
      }
      info = JSON.parse(JSON.stringify(userinfo))
        // res.json(resObj)
        resinfo(res,0,'获取成功',{info})
      },
      //注册相关逻辑
      userRegister:async (req,res)=>{

        let {phone,password} = req.body
        if(phone===''||password===''){
          resinfo(res,1,'数据不能为空')
        }
        // resinfo(res,1,'数据')
        // console.log(phone,password);
        let res1 = await userModel.find({phone})
        if(res1.length){
          resinfo(res,3,'手机号被占用')
          return
        }

        let res2 = await userModel.insertMany({
          userName:Math.random().toString(36).slice(-6),
          password: bcryptjs.hashSync(password,10),
          phone,
        })
        if(res2.length){
          resinfo(res,0,'注册成功')
        }else{
          resinfo(res,2,'注册失败，请刷新后重新注册')
        }
      },
      //登录相关逻辑
      userLogin: async (req,res)=>{
        let {phone,password} = req.body
        if(!phone||!password){
          resinfo(res,1,'数据不能为空')
          return
        }
        let res3 = await userModel.find({phone})
        if(!res3.length){
          resinfo(res,2,'该手机号码未注册')
          return
        }
        let userPass = res3[0].password
        let bool = bcryptjs.compareSync(password,userPass)
        if(bool){
          let token = jwt.sign({
            phone:res3[0].phone,
            startTime:+new Date(),
            expires:7200*1000
          },'ZB&&LXX&&CSJ&&ZLF&&ZWC&&YYZ&&CKN&&CDY')
          resinfo(res,0,'登录成功',{token,userId:res3[0]._id})
          return
        }else{
          resinfo(res,'3','用户名或者密码错误')
          return
        }
      },
      //修改密码
      userPass: async (req, res) => {
       
        // 接收id
        let userid = req.params.id
        // 接收密码
        let {oldpass, newpass} = req.body
        // 验证旧密码
        // 根据用户id查询用户信息
        let userData
        try{
            userData = await userModel.findOne({
                _id: userid
            })
        } catch(err) {
            resinfo(res,1,'手机号有误')
            return
        }
        // 验证旧密码
        let bool = bcryptjs.compareSync(oldpass, userData.password)
        // 判断
        if(bool) {
            // 改密码
            try{
                await userModel.updateOne({
                    _id: userid
                }, {$set: {
                    password: bcryptjs.hashSync(newpass, 10)
                }})
            } catch(err) {
                resinfo(res,3,'修改失败')
                return
            }
            resinfo(res,0,'修改成功')
        } else {
            resinfo(res,2,'旧密码有误')
            return
        }
    },
    //后台获取所有用户信息列表
    getUser: async(req,res)=>{
      let listResult = await userModel.find()
      if(listResult.length){
        resinfo(res,0,'获取成功',{listResult,})
      }else{
        resinfo(res,1,'获取失败，请刷新后重试')
      }
    },
    //后台删除用户信息
    remUser:async(req,res)=>{
      let {id} = req.body
      try {
        await userModel.deleteOne({_id:id})
        resinfo(res,0,'删除成功')
      } catch (error) {
        resinfo(res,1,'删除失败，缺少参数')
      }
    }
}